<?php

namespace App\Models;

use App\Logic\point\Point;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MinerInfo extends Model
{

    protected $table = 'miner_info';
    public $timestamps = false;

    //添加矿机
    public static function add($arr){


        $time = time();
        $host = DB::table('miner_host')
            ->where('token','FIL')
            ->where('end_time','>',$time)
            ->sum('hspace');
        $all_host = $host + $arr['hspace'];
        $origin = Point::curl();
        if($origin['status'] == 'ERROR'){
            return $origin;
        }else{
            if($origin['data']['code'] == 0 ){
                return e_msg(3202300,'请求您的总容量失败');
            }else{
                if($all_host>$origin['data']['data']){
                    return e_msg(3202300,'可用总容量为'.$origin['data']['data'].'已超出限额，请联系官方客服扩容');
                }
            }
        }


        $prefix = 'ZXY';
        $m_number_res = self::m_number($prefix);
        $m_number = $prefix . $m_number_res;

        $m_pass = rand(100000, 999999);
        $add_token = self::add_token();

        $miner_info_insert_arr = [
            'm_number' => $m_number,
            'm_pass' => $m_pass,
            'm_type' => $arr['capacity'],
            'note' => $arr['note'],
            'add_token' => $add_token,
        ];
        $mid = DB::table('miner_info')->insertGetId($miner_info_insert_arr);

        $miner_host_insert_arr[] = [

            'mid' => $mid,
            'start_time' => $arr['start_time'],
            'end_time' => $arr['end_time'],
            'token' => $arr['token'],
            'hspace' => $arr['hspace'],
            'hostrate' => $arr['hostrate'],
            'genuine' => $arr['genuine'],
        ];

        //添加托管记录和用户绑定矿机信息
        DB::table('miner_host')->insert($miner_host_insert_arr);
        return s_msg("添加矿机成功");

    }

    //绑定用户
    public static function bind($arr){

        $miner_user_insert_arr[] = [
            'mid' => $arr['mid'],
            'user_name' => $arr['user_name'],
            'note' => $arr['note'],
            'accessory' => $arr['accessory'],
        ];
        //添加托管记录和用户绑定矿机信息
        DB::table('miner_user')->insert($miner_user_insert_arr);
        //1.升级用户状态
        //2.给有等级的用户发奖励
        $host = DB::table('miner_host')
            ->where('mid','=',$arr['mid'])
            ->value('hspace');
        $history = DB::table('miner_host as mh')
            ->leftJoin('miner_user as mu','mu.mid','=','mh.mid')
            ->where('mu.user_name','=',$arr['user_name'])
            ->sum('mh.hspace');


        if($history>=10 && $history<1700){
            $state = 2;
        }elseif($history >= 1700){
            $state = 3;
        }else{
            $state = 1;
        }


        $user = DB::table('user')->where('username',$arr['user_name'])->select('state','state_lock','path','username','phone')->first();
        if($state != $user->state && $user->state_lock == 0 ){
            DB::table('user')->where('username',$arr['user_name'])->update(['state'=>$state]);
        }
        $path = rtrim($user->path,',');
        $path = ltrim($path,0);
        $path = ltrim($path,',');
        if(!$path){
            return s_msg("绑定用户成功");
        }
        $arr = explode(',',$path);
        $arr = array_reverse($arr);
        $count = count($arr);
        $state_start = 0;
        $cal = [
            1 => 0,
            2 => 15,
            3 => 30,
        ];
        $fil_insert_arr = [];
        if($count>0){
            for($i=0;$i<$count;$i++){
                $p = DB::table('user')->where('id',$arr[$i])->select('state','username','phone','id')->first();

                if($p->state > $state_start){

                    $calcute = $cal[$state];
                    $amount = $host * $calcute/100;
                    $fil_insert_arr[] = [
                        'out_account' => $p->username,
                        'out_phone' => $p->phone,
                        'shift_account' =>  $user->username,
                        'shift_phone' => $user->phone,
                        'amount' => abs($amount),
                        'type_note' => '算力奖励',
                        'type' => 'red',
                        'coin_type' => 'red',
                    ];

                    DB::table('user')->where('id',$p->id)->increment('red',$amount);
                    $state_start = $state;

                }

                if($state_start >= 3){
                    break;
                }

            }
        }

        if(count($fil_insert_arr) > 0){
            DB::table('record_fil')->insert($fil_insert_arr);
        }

        return s_msg("绑定用户成功");

    }


    //删除已绑定的矿机
    public static function miner_delete($id){

        $user_info = DB::table("user")->where("id",$id)->select('username','state')->first();
        if(!$user_info){
            return e_msg('此用户不存在');
        }else{
            if($user_info->state!=2){
                return e_msg("此用户没有绑定矿机,或者已锁定");
            }
            $username = $user_info->username;
        }

        $mid = DB::table('usermid')->where('userid',$username)->value('mid');

        DB::table('usermid')->where('mid',$mid)->delete();

        DB::table('minerhost')->where('mid',$mid)->delete();

        DB::table('minerinfo')->where('mid',$mid)->delete();

        DB::table('user')->where('id',$id)->update(['state'=>0,'hosting_time'=>null ]);
        DB::table('tui_user')->where('username',$username)->update(['state'=>0]);

        return s_msg("取消托管成功");

    }


    //矿机不重复编号
    public static function m_number($token){

        $token = 'ZXY';

        $value = self::where('m_number','like',$token."%")
            ->orderByDesc('mid')
            ->value('m_number');

        if($value){

            $len_1 = strlen($token);
            $len_2 = strlen($value);

            $zhongjian = substr($value,$len_1,$len_2);

            $ll = intval($zhongjian)+1;
            $c  = str_pad($ll,$len_2-$len_1,'0',STR_PAD_LEFT);

            $m_number = $c;

        }else{
            $m_number = '00000001';
        }
        return $m_number;
    }

    public static function add_token(){

        do {
            $add_token = GetRandStr(20);
            $re = self::where('add_token',$add_token)->value('mid');
        } while ($re);

        return $add_token;

    }



}
